import React from 'react';
import Redirect from 'umi/redirect';
import { connect } from 'dva';
import pathToRegexp from 'path-to-regexp';
import { ConnectProps, ConnectState, Route, UserModelState } from '@/models/connect';

interface AuthComponentProps extends ConnectProps {
  user: UserModelState;
  children: any;
}

const testMatch = (path: string, routeData: Route[]): boolean => {
  if (pathToRegexp(`/exception(.*)`).test(path)) {
    return true;
  }

  let result = false;
  const deep = (path: string, routeData: Route[]): any => {
    for (let route of routeData) {
      if (pathToRegexp(`${route.path}(.*)`).test(path)) {
        //先检查父路由有没有匹配
        if (pathToRegexp(`${route.path}`).test(path)) {
          result = true;
          break;
        }
        if (route.children) {
          deep(path, route.children);
        }
      }
    }
  };
  deep(path, routeData);
  return result;
};

// const isMatch = (path: string, routeData: Route[]): boolean => {
//   if (pathToRegexp(`/exception(.*)`).test(path)) {
//     return true;
//   }
//   let match: boolean = false;
//   routeData.forEach(route => {
//     if (pathToRegexp(`${route.path}`).test(path)) {
//       match = true;
//     }
//   });
//   return match;
// };

const AuthComponent: React.FC<AuthComponentProps> = ({
  children,
  route = { routes: [] },
  location = { pathname: '' },
  user,
}) => {
  const { isFetchMenu, menuData } = user;
  // const { routes = [] } = route;
  // console.log('authorities');
  // console.log(routes);
  // const routesData = [
  //   {
  //     path: '/articles',
  //   },
  //   {
  //     path: '/articles/list',
  //   },
  //   {
  //     path: '/articles/publish',
  //   },
  //   {
  //     path: '/articles/edit',
  //   },
  //   {
  //     path: '/welcome',
  //   }
  // ];

  // const routesData = [
  //   {
  //     path: '/articles',
  //     children: [
  //       {
  //         path: '/articles/list',
  //       },
  //       {
  //         path: '/articles/publish',
  //       },
  //       {
  //         path: '/articles/edit',
  //       },
  //     ],
  //   },
  //
  //   {
  //     path: '/welcome',
  //     children: [
  //       {
  //         path: '/welcome/list',
  //       },
  //       {
  //         path: '/welcome/publish',
  //       },
  //       {
  //         path: '/welcome/edit',
  //       },
  //     ],
  //   },
  // ];

  // console.log('testMatch');
  // console.log(testMatch('/welcome/publish', routesData));
  // const matchResult: boolean = isMatch(location.pathname, routes);
  const matchResult: boolean = testMatch(location.pathname, menuData as Route[]);

  const whiteUrls = ['/'];
  if (!whiteUrls.includes(location.pathname) && isFetchMenu && !matchResult) {
    // return <Exception403 />
    console.log('403');
    return <Redirect to="/exception/403" />;
  }
  return children;
};

export default connect(({ user }: ConnectState) => ({
  user,
}))(AuthComponent);
